<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mock服务管理</title>
    <link href="../css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/bootstrap-icons.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background-color: #f8f9fa;
        }
        .content {
            padding: 20px;
        }
        .card {
            margin-bottom: 20px;
        }
        .btn-group-sm > .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-3 col-lg-2 sidebar p-3">
                <h4 class="mb-4">Mock服务管理</h4>
                <div class="list-group">
                    <a href="#" class="list-group-item list-group-item-action active" onclick="showGroups()">
                        <i class="bi bi-collection"></i> 分组管理
                    </a>
                    <a href="#" class="list-group-item list-group-item-action" onclick="showApis()">
                        <i class="bi bi-code-slash"></i> 接口管理
                    </a>
                </div>
            </div>

            <!-- 主内容区 -->
            <div class="col-md-9 col-lg-10 content">
                <!-- 分组管理 -->
                <div id="groups-section">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h3>分组管理</h3>
                        <button class="btn btn-primary" onclick="showAddGroupModal()">
                            <i class="bi bi-plus"></i> 新增分组
                        </button>
                    </div>
                    <div id="groups-list"></div>
                </div>

                <!-- 接口管理 -->
                <div id="apis-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h3>接口管理</h3>
                        <div class="btn-group">
                            <button class="btn btn-outline-success" onclick="showExportModal()">
                                <i class="bi bi-download"></i> 导出数据
                            </button>
                            <button class="btn btn-outline-info" onclick="showImportModal()">
                                <i class="bi bi-upload"></i> 导入数据
                            </button>
                            <button class="btn btn-primary" onclick="showAddApiModal()">
                                <i class="bi bi-plus"></i> 新增接口
                            </button>
                        </div>
                    </div>
                    
                    <!-- 分组筛选 -->
                    <div class="card mb-3">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-4">
                                    <label class="form-label">按分组筛选</label>
                                    <select class="form-select" id="groupFilter" onchange="filterApisByGroup()">
                                        <option value="">全部分组</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">按状态筛选</label>
                                    <select class="form-select" id="statusFilter" onchange="filterApisByStatus()">
                                        <option value="">全部状态</option>
                                        <option value="true">启用</option>
                                        <option value="false">禁用</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">搜索接口</label>
                                    <input type="text" class="form-control" id="apiSearch" placeholder="输入接口名称或路径" onkeyup="searchApis()">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div id="apis-list"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- 新增分组模态框 -->
    <div class="modal fade" id="addGroupModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">新增分组</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addGroupForm">
                        <div class="mb-3">
                            <label class="form-label">分组名称</label>
                            <input type="text" class="form-control" name="groupName" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">描述</label>
                            <textarea class="form-control" name="description" rows="3"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">排序</label>
                            <input type="number" class="form-control" name="sortOrder" value="0">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addGroup()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑分组模态框 -->
    <div class="modal fade" id="editGroupModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑分组</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editGroupForm">
                        <input type="hidden" name="id">
                        <div class="mb-3">
                            <label class="form-label">分组名称</label>
                            <input type="text" class="form-control" name="groupName" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">描述</label>
                            <textarea class="form-control" name="description" rows="3"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">排序</label>
                            <input type="number" class="form-control" name="sortOrder" value="0">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">状态</label>
                            <select class="form-select" name="enabled">
                                <option value="true">启用</option>
                                <option value="false">禁用</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="updateGroup()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 新增接口模态框 -->
    <div class="modal fade" id="addApiModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">新增接口</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addApiForm">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">分组</label>
                                    <select class="form-select" name="groupId" required>
                                        <option value="">请选择分组</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">接口名称</label>
                                    <input type="text" class="form-control" name="apiName" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">接口路径</label>
                                    <input type="text" class="form-control" name="apiPath" placeholder="/api/example" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">HTTP方法</label>
                                    <select class="form-select" name="httpMethod" required>
                                        <option value="GET">GET</option>
                                        <option value="POST">POST</option>
                                        <option value="PUT">PUT</option>
                                        <option value="DELETE">DELETE</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">状态码</label>
                                    <input type="number" class="form-control" name="statusCode" value="200">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">延迟(毫秒)</label>
                                    <input type="number" class="form-control" name="delayMs" value="0">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">排序</label>
                                    <input type="number" class="form-control" name="sortOrder" value="0">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">真实服务URL <small class="text-muted">(可选)</small></label>
                                    <input type="url" class="form-control" name="realUrl" placeholder="https://api.example.com/users">
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">请求参数示例</label>
                            <textarea class="form-control" name="requestParams" rows="3" placeholder="{}"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">参数匹配规则 <small class="text-muted">(JSON格式，留空则不进行参数匹配)</small></label>
                            <textarea class="form-control" name="paramMatchRules" rows="3" placeholder='{"userType": "VIP"}'></textarea>
                            <div class="form-text">
                                示例：<code>{"userType": "VIP", "level": "1"}</code><br>
                                当请求参数包含 userType=VIP 且 level=1 时，返回此接口的响应
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">响应数据</label>
                            <textarea class="form-control" name="responseData" rows="5" placeholder="{}" required></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addApi()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑接口模态框 -->
    <div class="modal fade" id="editApiModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑接口</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editApiForm">
                        <input type="hidden" name="id">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">分组</label>
                                    <select class="form-select" name="groupId" required>
                                        <option value="">请选择分组</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">接口名称</label>
                                    <input type="text" class="form-control" name="apiName" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">接口路径</label>
                                    <input type="text" class="form-control" name="apiPath" placeholder="/api/example" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">HTTP方法</label>
                                    <select class="form-select" name="httpMethod" required>
                                        <option value="GET">GET</option>
                                        <option value="POST">POST</option>
                                        <option value="PUT">PUT</option>
                                        <option value="DELETE">DELETE</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">状态码</label>
                                    <input type="number" class="form-control" name="statusCode" value="200">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">延迟(毫秒)</label>
                                    <input type="number" class="form-control" name="delayMs" value="0">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">排序</label>
                                    <input type="number" class="form-control" name="sortOrder" value="0">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">状态</label>
                                    <select class="form-select" name="enabled">
                                        <option value="true">启用</option>
                                        <option value="false">禁用</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">真实服务URL <small class="text-muted">(可选)</small></label>
                                    <input type="url" class="form-control" name="realUrl" placeholder="https://api.example.com/users">
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">请求参数示例</label>
                            <textarea class="form-control" name="requestParams" rows="3" placeholder="{}"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">参数匹配规则 <small class="text-muted">(JSON格式，留空则不进行参数匹配)</small></label>
                            <textarea class="form-control" name="paramMatchRules" rows="3" placeholder='{"userType": "VIP"}'></textarea>
                            <div class="form-text">
                                示例：<code>{"userType": "VIP", "level": "1"}</code><br>
                                当请求参数包含 userType=VIP 且 level=1 时，返回此接口的响应
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">响应数据</label>
                            <textarea class="form-control" name="responseData" rows="5" placeholder="{}" required></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="updateApi()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 获取当前页面的上下文路径（去掉最后的 /index.html 或 /）
        const getCurrentContextPath = () => {
            const path = window.location.pathname;
            // 如果路径是 /svr/ 或 /svr/index.html，返回 /svr
            const pathParts = path.split('/').filter(p => p);
            if (pathParts.length === 0) return '';
            // 假设你的页面在上下文根目录下，比如 /svr/index.html
            if (pathParts[0] === 'mockPage')
                return '';
            else return '/' + pathParts[0]; // 返回 /svr
        };

        const APP_CONTEXT_PATH = getCurrentContextPath();
    </script>
    <script src="../js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量
        let currentGroups = [];
        let currentApis = [];

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadGroups();
            loadApis();
        });

        // 显示分组管理
        function showGroups() {
            document.getElementById('groups-section').style.display = 'block';
            document.getElementById('apis-section').style.display = 'none';
            document.querySelectorAll('.list-group-item').forEach(item => item.classList.remove('active'));
            event.target.classList.add('active');
        }

        // 显示接口管理
        function showApis() {
            document.getElementById('groups-section').style.display = 'none';
            document.getElementById('apis-section').style.display = 'block';
            document.querySelectorAll('.list-group-item').forEach(item => item.classList.remove('active'));
            event.target.classList.add('active');
        }

        // 加载分组列表
        async function loadGroups() {
            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/mock/group/list`);
                currentGroups = await response.json();
                renderGroups();
                updateGroupSelect();
            } catch (error) {
                console.error('加载分组失败:', error);
            }
        }

        // 加载接口列表
        async function loadApis() {
            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/mock/api/list`);
                currentApis = await response.json();
                renderApis();
            } catch (error) {
                console.error('加载接口失败:', error);
            }
        }

        // 渲染分组列表
        function renderGroups() {
            const container = document.getElementById('groups-list');
            if (currentGroups.length === 0) {
                container.innerHTML = '<div class="alert alert-info">暂无分组数据</div>';
                return;
            }

            const html = currentGroups.map(group => `
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h5 class="card-title">${group.groupName}</h5>
                                <p class="card-text text-muted">${group.description || '暂无描述'}</p>
                                <small class="text-muted">排序: ${group.sortOrder} | 状态: ${group.enabled ? '启用' : '禁用'}</small>
                            </div>
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-outline-info" onclick="exportGroupData(${group.id})" title="导出分组数据">
                                    <i class="bi bi-download"></i>
                                </button>
                                <button class="btn btn-outline-success" onclick="fetchGroupRealData(${group.id})" title="拉取分组真实数据">
                                    <i class="bi bi-cloud-download"></i>
                                </button>
                                <button class="btn btn-outline-primary" onclick="editGroup(${group.id})">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <button class="btn btn-outline-danger" onclick="deleteGroup(${group.id})">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `).join('');

            container.innerHTML = html;
        }



        // 更新分组选择器
        function updateGroupSelect() {
            const select = document.querySelector('select[name="groupId"]');
            const groupFilter = document.getElementById('groupFilter');
            
            select.innerHTML = '<option value="">请选择分组</option>';
            groupFilter.innerHTML = '<option value="">全部分组</option>';
            
            currentGroups.forEach(group => {
                select.innerHTML += `<option value="${group.id}">${group.groupName}</option>`;
                groupFilter.innerHTML += `<option value="${group.id}">${group.groupName}</option>`;
            });
        }

        // 显示新增分组模态框
        function showAddGroupModal() {
            document.getElementById('addGroupForm').reset();
            new bootstrap.Modal(document.getElementById('addGroupModal')).show();
        }

        // 显示编辑分组模态框
        function editGroup(id) {
            const group = currentGroups.find(g => g.id === id);
            if (group) {
                const form = document.getElementById('editGroupForm');
                form.querySelector('input[name="id"]').value = group.id;
                form.querySelector('input[name="groupName"]').value = group.groupName;
                form.querySelector('textarea[name="description"]').value = group.description || '';
                form.querySelector('input[name="sortOrder"]').value = group.sortOrder || 0;
                form.querySelector('select[name="enabled"]').value = group.enabled.toString();
                
                new bootstrap.Modal(document.getElementById('editGroupModal')).show();
            }
        }

        // 显示新增接口模态框
        function showAddApiModal() {
            document.getElementById('addApiForm').reset();
            new bootstrap.Modal(document.getElementById('addApiModal')).show();
        }

        // 新增分组
        async function addGroup() {
            const form = document.getElementById('addGroupForm');
            const formData = new FormData(form);
            const data = {
                groupName: formData.get('groupName'),
                description: formData.get('description'),
                sortOrder: parseInt(formData.get('sortOrder')) || 0,
                enabled: true
            };

            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/mock/group`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    bootstrap.Modal.getInstance(document.getElementById('addGroupModal')).hide();
                    loadGroups();
                    showAlert('分组创建成功', 'success');
                } else {
                    showAlert('分组创建失败', 'danger');
                }
            } catch (error) {
                console.error('创建分组失败:', error);
                showAlert('创建分组失败', 'danger');
            }
        }

        // 更新分组
        async function updateGroup() {
            const form = document.getElementById('editGroupForm');
            const formData = new FormData(form);
            
            const oldGroup = currentGroups.find(g => g.id == formData.get('id'));
            const newEnabled = formData.get('enabled') === 'true';
            const statusChanged = oldGroup && oldGroup.enabled !== newEnabled;
            
            const data = {
                groupName: formData.get('groupName'),
                description: formData.get('description'),
                sortOrder: parseInt(formData.get('sortOrder')) || 0,
                enabled: newEnabled
            };

            const id = formData.get('id');

            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/mock/group/${id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    bootstrap.Modal.getInstance(document.getElementById('editGroupModal')).hide();
                    loadGroups();
                    
                    // 如果分组状态发生变化，重新加载接口列表以显示状态变化
                    if (statusChanged) {
                        loadApis();
                        const statusText = newEnabled ? '启用' : '禁用';
                        showAlert(`分组更新成功，该分组下的所有接口已同时${statusText}`, 'success');
                    } else {
                        showAlert('分组更新成功', 'success');
                    }
                } else {
                    showAlert('分组更新失败', 'danger');
                }
            } catch (error) {
                console.error('更新分组失败:', error);
                showAlert('更新分组失败', 'danger');
            }
        }

        // 新增接口
        async function addApi() {
            const form = document.getElementById('addApiForm');
            const formData = new FormData(form);
            
            // 验证参数匹配规则格式
            const paramMatchRules = formData.get('paramMatchRules')?.trim();
            if (paramMatchRules && !validateJsonFormat(paramMatchRules)) {
                showAlert('参数匹配规则格式错误，请输入有效的JSON格式', 'danger');
                return;
            }
            
            const data = {
                groupId: parseInt(formData.get('groupId')),
                apiName: formData.get('apiName'),
                apiPath: formData.get('apiPath'),
                httpMethod: formData.get('httpMethod'),
                requestParams: formData.get('requestParams') || '{}',
                paramMatchRules: paramMatchRules || null,
                realUrl: formData.get('realUrl') || null,
                responseData: formData.get('responseData'),
                statusCode: parseInt(formData.get('statusCode')) || 200,
                delayMs: parseInt(formData.get('delayMs')) || 0,
                sortOrder: parseInt(formData.get('sortOrder')) || 0,
                enabled: true
            };

            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/mock/api`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    bootstrap.Modal.getInstance(document.getElementById('addApiModal')).hide();
                    loadApis();
                    showAlert('接口创建成功', 'success');
                } else {
                    showAlert('接口创建失败', 'danger');
                }
            } catch (error) {
                console.error('创建接口失败:', error);
                showAlert('创建接口失败', 'danger');
            }
        }

        // 删除分组
        async function deleteGroup(id) {
            const group = currentGroups.find(g => g.id === id);
            const groupApis = currentApis.filter(api => api.groupId === id);
            
            let confirmMessage = `确定要删除分组 "${group?.groupName || '未知'}" 吗？`;
            if (groupApis.length > 0) {
                confirmMessage += `\n\n注意：该分组下有 ${groupApis.length} 个接口，删除分组会同时删除这些接口！`;
            }
            
            if (!confirm(confirmMessage)) return;

            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/mock/group/${id}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    loadGroups();
                    loadApis(); // 重新加载接口列表，因为可能有接口被删除
                    showAlert('分组删除成功', 'success');
                } else {
                    showAlert('分组删除失败', 'danger');
                }
            } catch (error) {
                console.error('删除分组失败:', error);
                showAlert('删除分组失败', 'danger');
            }
        }

        // 删除接口
        async function deleteApi(id) {
            if (!confirm('确定要删除这个接口吗？')) return;

            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/mock/api/${id}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    loadApis();
                    showAlert('接口删除成功', 'success');
                } else {
                    showAlert('接口删除失败', 'danger');
                }
            } catch (error) {
                console.error('删除接口失败:', error);
                showAlert('删除接口失败', 'danger');
            }
        }

        // 编辑接口
        function editApi(id) {
            const api = currentApis.find(a => a.id === id);
            if (api) {
                const form = document.getElementById('editApiForm');
                form.querySelector('input[name="id"]').value = api.id;
                form.querySelector('input[name="apiName"]').value = api.apiName;
                form.querySelector('input[name="apiPath"]').value = api.apiPath;
                form.querySelector('select[name="httpMethod"]').value = api.httpMethod;
                form.querySelector('select[name="groupId"]').value = api.groupId;
                form.querySelector('input[name="statusCode"]').value = api.statusCode || 200;
                form.querySelector('input[name="delayMs"]').value = api.delayMs || 0;
                form.querySelector('input[name="sortOrder"]').value = api.sortOrder || 0;
                form.querySelector('select[name="enabled"]').value = api.enabled.toString();
                form.querySelector('input[name="realUrl"]').value = api.realUrl || '';
                form.querySelector('textarea[name="requestParams"]').value = api.requestParams || '{}';
                form.querySelector('textarea[name="paramMatchRules"]').value = api.paramMatchRules || '';
                form.querySelector('textarea[name="responseData"]').value = api.responseData || '{}';
                
                // 更新编辑表单中的分组选择器
                updateEditApiGroupSelect();
                
                new bootstrap.Modal(document.getElementById('editApiModal')).show();
            }
        }

        // 更新接口
        async function updateApi() {
            const form = document.getElementById('editApiForm');
            const formData = new FormData(form);
            
            // 验证参数匹配规则格式
            const paramMatchRules = formData.get('paramMatchRules')?.trim();
            if (paramMatchRules && !validateJsonFormat(paramMatchRules)) {
                showAlert('参数匹配规则格式错误，请输入有效的JSON格式', 'danger');
                return;
            }
            
            const data = {
                groupId: parseInt(formData.get('groupId')),
                apiName: formData.get('apiName'),
                apiPath: formData.get('apiPath'),
                httpMethod: formData.get('httpMethod'),
                requestParams: formData.get('requestParams') || '{}',
                paramMatchRules: paramMatchRules || null,
                realUrl: formData.get('realUrl') || null,
                responseData: formData.get('responseData'),
                statusCode: parseInt(formData.get('statusCode')) || 200,
                delayMs: parseInt(formData.get('delayMs')) || 0,
                sortOrder: parseInt(formData.get('sortOrder')) || 0,
                enabled: formData.get('enabled') === 'true'
            };

            const id = formData.get('id');

            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/mock/api/${id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    bootstrap.Modal.getInstance(document.getElementById('editApiModal')).hide();
                    loadApis();
                    showAlert('接口更新成功', 'success');
                } else {
                    showAlert('接口更新失败', 'danger');
                }
            } catch (error) {
                console.error('更新接口失败:', error);
                showAlert('更新接口失败', 'danger');
            }
        }

        // 更新编辑表单中的分组选择器
        function updateEditApiGroupSelect() {
            const select = document.querySelector('#editApiForm select[name="groupId"]');
            select.innerHTML = '<option value="">请选择分组</option>';
            
            currentGroups.forEach(group => {
                select.innerHTML += `<option value="${group.id}">${group.groupName}</option>`;
            });
        }

        // 切换接口状态
        async function toggleApiStatus(id, enabled) {
            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/mock/api/${id}/status?enabled=${enabled}`, {
                    method: 'PUT'
                });

                if (response.ok) {
                    loadApis();
                    showAlert(`接口${enabled ? '启用' : '禁用'}成功`, 'success');
                } else {
                    showAlert(`接口${enabled ? '启用' : '禁用'}失败`, 'danger');
                }
            } catch (error) {
                console.error('切换接口状态失败:', error);
                showAlert('切换接口状态失败', 'danger');
            }
        }

        // 验证JSON格式
        function validateJsonFormat(jsonString) {
            try {
                JSON.parse(jsonString);
                return true;
            } catch (error) {
                return false;
            }
        }

        // 显示提示信息
        function showAlert(message, type) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
            alertDiv.style.top = '20px';
            alertDiv.style.right = '20px';
            alertDiv.style.zIndex = '9999';
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            document.body.appendChild(alertDiv);

            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 3000);
        }

        // 按分组筛选接口
        function filterApisByGroup() {
            renderFilteredApis();
        }

        // 按状态筛选接口
        function filterApisByStatus() {
            renderFilteredApis();
        }

        // 搜索接口
        function searchApis() {
            renderFilteredApis();
        }

        // 渲染筛选后的接口列表
        function renderFilteredApis() {
            const groupFilter = document.getElementById('groupFilter').value;
            const statusFilter = document.getElementById('statusFilter').value;
            const searchText = document.getElementById('apiSearch').value.toLowerCase();

            let filteredApis = currentApis.filter(api => {
                // 分组筛选
                if (groupFilter && api.groupId != groupFilter) {
                    return false;
                }
                
                // 状态筛选
                if (statusFilter && api.enabled.toString() !== statusFilter) {
                    return false;
                }
                
                // 搜索筛选
                if (searchText) {
                    const apiName = api.apiName.toLowerCase();
                    const apiPath = api.apiPath.toLowerCase();
                    if (!apiName.includes(searchText) && !apiPath.includes(searchText)) {
                        return false;
                    }
                }
                
                return true;
            });

            renderApis(filteredApis);
        }

        // 重载渲染接口列表函数，支持传入筛选后的数据
        function renderApis(apisToRender = null) {
            const apis = apisToRender || currentApis;
            const container = document.getElementById('apis-list');
            
            if (apis.length === 0) {
                container.innerHTML = '<div class="alert alert-info">暂无接口数据</div>';
                return;
            }

            const html = apis.map(api => {
                const group = currentGroups.find(g => g.id === api.groupId);
                const hasParamRules = api.paramMatchRules && api.paramMatchRules.trim();
                const hasRealUrl = api.realUrl && api.realUrl.trim();
                const paramRulesDisplay = hasParamRules 
                    ? `<br><small class="text-info"><i class="bi bi-funnel"></i> 参数匹配: ${api.paramMatchRules}</small>` 
                    : '';
                const realUrlDisplay = hasRealUrl
                    ? `<br><small class="text-success"><i class="bi bi-cloud"></i> 真实URL: ${api.realUrl}</small>`
                    : '';
                    
                return `
                    <div class="card">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="card-title">
                                        ${api.apiName}
                                        ${hasParamRules ? '<span class="badge bg-info ms-2">参数匹配</span>' : ''}
                                        ${hasRealUrl ? '<span class="badge bg-success ms-2">真实URL</span>' : ''}
                                    </h6>
                                    <p class="card-text">
                                        <code>${api.httpMethod} ${api.apiPath}</code><br>
                                        <small class="text-muted">分组: ${group ? group.groupName : '未知'} | 状态码: ${api.statusCode} | 延迟: ${api.delayMs}ms</small>
                                        ${paramRulesDisplay}
                                        ${realUrlDisplay}
                                    </p>
                                </div>
                                <div class="btn-group btn-group-sm">
                                    ${hasRealUrl ? `<button class="btn btn-outline-info" onclick="showFetchRealDataModal(${api.id})" title="拉取真实数据">
                                        <i class="bi bi-cloud-download"></i>
                                    </button>` : ''}
                                    <button class="btn btn-outline-success" onclick="toggleApiStatus(${api.id}, ${!api.enabled})">
                                        <i class="bi bi-${api.enabled ? 'pause' : 'play'}"></i>
                                    </button>
                                    <button class="btn btn-outline-primary" onclick="editApi(${api.id})">
                                        <i class="bi bi-pencil"></i>
                                    </button>
                                    <button class="btn btn-outline-danger" onclick="deleteApi(${api.id})">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            }).join('');

            container.innerHTML = html;
        }
    </script>

    <!-- 数据导出模态框 -->
    <div class="modal fade" id="exportModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">导出Mock数据</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>将导出所有分组和接口数据到JSON文件。</p>
                    <div class="alert alert-info">
                        <i class="bi bi-info-circle"></i>
                        导出的数据可以在其他环境导入，实现Mock配置的迁移。
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-success" onclick="exportData()">
                        <i class="bi bi-download"></i> 导出
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 数据导入模态框 -->
    <div class="modal fade" id="importModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">导入Mock数据</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="importForm" enctype="multipart/form-data">
                        <div class="mb-3">
                            <label class="form-label">选择JSON文件</label>
                            <input type="file" class="form-control" name="file" accept=".json" required onchange="previewImport()">
                            <div class="form-text">
                                请选择从其他环境导出的Mock数据JSON文件
                            </div>
                        </div>
                        
                        <!-- 预览区域 -->
                        <div id="importPreview" style="display: none;">
                            <hr>
                            <h6>文件预览</h6>
                            <div id="previewInfo" class="mb-3"></div>
                            
                            <div class="mb-3">
                                <label class="form-label">导入模式</label>
                                <div>
                                    <input type="radio" id="importAll" name="importMode" value="all" checked onchange="toggleGroupSelection()">
                                    <label for="importAll" class="form-label">导入全部</label>
                                </div>
                                <div>
                                    <input type="radio" id="importSelected" name="importMode" value="selected" onchange="toggleGroupSelection()">
                                    <label for="importSelected" class="form-label">选择性导入</label>
                                </div>
                            </div>
                            
                            <div id="groupSelection" style="display: none;" class="mb-3">
                                <label class="form-label">选择要导入的分组</label>
                                <div class="border rounded p-2" style="max-height: 400px; overflow-y: auto;">
                                    <div id="groupCheckboxes"></div>
                                </div>
                                <div class="form-text mt-2">
                                    <small class="text-info">
                                        <i class="bi bi-info-circle"></i> 
                                        可以在导入时重新设置分组名称和描述
                                    </small>
                                </div>
                            </div>
                        </div>
                    </form>
                    <div id="importResult" class="mt-3" style="display: none;"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-info" onclick="importData()" id="importBtn" disabled>
                        <i class="bi bi-upload"></i> 导入
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 拉取真实数据模态框 -->
    <div class="modal fade" id="fetchRealDataModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">拉取真实数据</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="fetchRealDataForm">
                        <input type="hidden" name="apiId">
                        <div class="mb-3">
                            <label class="form-label">接口信息</label>
                            <div class="card">
                                <div class="card-body">
                                    <div id="apiInfo"></div>
                                </div>
                            </div>
                        </div>
                        <div id="fetchResult" style="display: none;">
                            <hr>
                            <h6>响应结果:</h6>
                            <textarea class="form-control" id="fetchedData" rows="8" readonly></textarea>
                            <div class="mt-2">
                                <button type="button" class="btn btn-success" onclick="applyFetchedData()">
                                    <i class="bi bi-check"></i> 应用到接口响应
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="fetchRealData()">
                        <i class="bi bi-cloud-download"></i> 拉取数据
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 导出数据功能
        function showExportModal() {
            new bootstrap.Modal(document.getElementById('exportModal')).show();
        }

        async function exportData() {
            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/mock/data/export`);
                if (response.ok) {
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.style.display = 'none';
                    a.href = url;
                    a.download = 'mock-data.json';
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                    
                    bootstrap.Modal.getInstance(document.getElementById('exportModal')).hide();
                    showAlert('数据导出成功', 'success');
                } else {
                    showAlert('数据导出失败', 'danger');
                }
            } catch (error) {
                console.error('导出数据失败:', error);
                showAlert('导出数据失败', 'danger');
            }
        }

        // 拉取真实数据功能
        function showFetchRealDataModal(apiId) {
            const api = currentApis.find(a => a.id === apiId);
            if (!api || !api.realUrl) {
                showAlert('该接口未配置真实URL', 'warning');
                return;
            }

            const form = document.getElementById('fetchRealDataForm');
            form.querySelector('input[name="apiId"]').value = apiId;
            
            // 显示接口信息
            const apiInfo = document.getElementById('apiInfo');
            apiInfo.innerHTML = `
                <p><strong>接口名称:</strong> ${api.apiName}</p>
                <p><strong>HTTP方法:</strong> ${api.httpMethod}</p>
                <p><strong>真实URL:</strong> ${api.realUrl}</p>
                <p><strong>请求参数:</strong></p>
                <pre class="bg-light p-2 rounded"><code>${api.requestParams || '{}'}</code></pre>
            `;
            
            document.getElementById('fetchResult').style.display = 'none';
            new bootstrap.Modal(document.getElementById('fetchRealDataModal')).show();
        }

        async function fetchRealData() {
            const form = document.getElementById('fetchRealDataForm');
            const apiId = parseInt(form.querySelector('input[name="apiId"]').value);
            
            const requestData = {
                apiId: apiId
            };

            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/mock/data/fetch-real`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });

                const result = await response.json();
                
                if (result.success) {
                    document.getElementById('fetchedData').value = result.data;
                    document.getElementById('fetchResult').style.display = 'block';
                    showAlert('真实数据拉取成功', 'success');
                } else {
                    showAlert(`拉取失败: ${result.message}`, 'danger');
                }
            } catch (error) {
                console.error('拉取真实数据失败:', error);
                showAlert('拉取真实数据失败', 'danger');
            }
        }

        function applyFetchedData() {
            const fetchedData = document.getElementById('fetchedData').value;
            const apiId = document.getElementById('fetchRealDataForm').querySelector('input[name="apiId"]').value;
            
            // 将拉取的数据应用到接口的响应数据中
            const api = currentApis.find(a => a.id == apiId);
            if (api) {
                // 更新接口的响应数据
                api.responseData = fetchedData;
                
                // 调用更新接口API
                updateApiWithFetchedData(api);
            }
        }

        async function updateApiWithFetchedData(api) {
            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/mock/api/${api.id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(api)
                });

                if (response.ok) {
                    bootstrap.Modal.getInstance(document.getElementById('fetchRealDataModal')).hide();
                    loadApis();
                    showAlert('真实数据已应用到接口响应', 'success');
                } else {
                    showAlert('应用真实数据失败', 'danger');
                }
            } catch (error) {
                console.error('应用真实数据失败:', error);
                showAlert('应用真实数据失败', 'danger');
            }
        }

        // 全局变量用于存储当前操作的分组ID
        let currentFetchGroupId = null;

        // 按分组导出数据
        async function exportGroupData(groupId) {
            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/mock/data/export?groupId=${groupId}`);
                if (response.ok) {
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.style.display = 'none';
                    a.href = url;
                    a.download = `mock-data-group-${groupId}.json`;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                    
                    showAlert('分组数据导出成功', 'success');
                } else {
                    showAlert('分组数据导出失败', 'danger');
                }
            } catch (error) {
                console.error('导出分组数据失败:', error);
                showAlert('导出分组数据失败', 'danger');
            }
        }

        // 显示分组批量拉取数据模态框
        function fetchGroupRealData(groupId) {
            currentFetchGroupId = groupId;
            const group = currentGroups.find(g => g.id === groupId);
            const groupApis = currentApis.filter(api => api.groupId === groupId);
            const realUrlApis = groupApis.filter(api => api.realUrl && api.realUrl.trim());
            
            if (realUrlApis.length === 0) {
                showAlert('该分组下没有配置真实URL的接口', 'warning');
                return;
            }
            
            const info = document.getElementById('groupFetchInfo');
            info.innerHTML = `
                <div class="alert alert-info">
                    <h6><i class="bi bi-info-circle"></i> 分组信息</h6>
                    <p><strong>分组名称:</strong> ${group.groupName}</p>
                    <p><strong>总接口数:</strong> ${groupApis.length}</p>
                    <p><strong>配置真实URL的接口:</strong> ${realUrlApis.length}</p>
                </div>
                <div class="mb-3">
                    <h6>将要拉取的接口列表:</h6>
                    <ul class="list-group">
                        ${realUrlApis.map(api => `
                            <li class="list-group-item">
                                <strong>${api.apiName}</strong>
                                <br><small class="text-muted">${api.httpMethod} ${api.apiPath}</small>
                                <br><small class="text-success">${api.realUrl}</small>
                            </li>
                        `).join('')}
                    </ul>
                </div>
            `;
            
            document.getElementById('groupFetchResult').style.display = 'none';
            document.getElementById('fetchGroupBtn').disabled = false;
            new bootstrap.Modal(document.getElementById('fetchGroupDataModal')).show();
        }

        // 确认执行分组批量拉取
        async function confirmFetchGroupData() {
            if (!currentFetchGroupId) return;
            
            document.getElementById('fetchGroupBtn').disabled = true;
            document.getElementById('fetchGroupBtn').innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> 拉取中...';
            
            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/mock/data/fetch-real-by-group`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        groupId: currentFetchGroupId
                    })
                });

                const result = await response.json();
                
                const resultDiv = document.getElementById('groupFetchResult');
                const detailsDiv = document.getElementById('groupFetchDetails');
                
                if (result.success) {
                    detailsDiv.innerHTML = `
                        <div class="alert alert-success">
                            <i class="bi bi-check-circle"></i>
                            ${result.message}
                        </div>
                        <div class="mb-3">
                            <h6>详细结果:</h6>
                            <ul class="list-group">
                                ${Object.entries(result.details).map(([apiName, status]) => `
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        ${apiName}
                                        <span class="badge ${status === '成功' ? 'bg-success' : 'bg-danger'}">${status}</span>
                                    </li>
                                `).join('')}
                            </ul>
                        </div>
                    `;
                    
                    // 刷新接口列表
                    loadApis();
                    showAlert('分组真实数据拉取完成', 'success');
                } else {
                    detailsDiv.innerHTML = `
                        <div class="alert alert-danger">
                            <i class="bi bi-exclamation-circle"></i>
                            ${result.message}
                        </div>
                    `;
                    showAlert('分组真实数据拉取失败', 'danger');
                }
                
                resultDiv.style.display = 'block';
                
            } catch (error) {
                console.error('批量拉取真实数据失败:', error);
                showAlert('批量拉取真实数据失败', 'danger');
            } finally {
                document.getElementById('fetchGroupBtn').disabled = false;
                document.getElementById('fetchGroupBtn').innerHTML = '<i class="bi bi-cloud-download"></i> 开始拉取';
            }
        }

        // 导入预览功能
        async function previewImport() {
            const form = document.getElementById('importForm');
            const formData = new FormData(form);
            const file = formData.get('file');
            
            if (!file) return;
            
            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/mock/data/import/preview`, {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                
                if (result.success) {
                    const previewDiv = document.getElementById('importPreview');
                    const infoDiv = document.getElementById('previewInfo');
                    
                    infoDiv.innerHTML = `
                        <div class="alert alert-info">
                            <h6><i class="bi bi-file-earmark-text"></i> 文件信息</h6>
                            <p><strong>版本:</strong> ${result.version}</p>
                            <p><strong>导出时间:</strong> ${new Date(result.exportTime).toLocaleString()}</p>
                            <p><strong>分组总数:</strong> ${result.totalGroups}</p>
                            <p><strong>接口总数:</strong> ${result.totalApis}</p>
                        </div>
                    `;
                    
                    // 构建分组选择列表
                    const checkboxesDiv = document.getElementById('groupCheckboxes');
                    checkboxesDiv.innerHTML = result.groups.map(group => `
                        <div class="card mb-2">
                            <div class="card-body p-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" value="${group.id}" id="group_${group.id}" onchange="toggleGroupRename(${group.id})">
                                    <label class="form-check-label" for="group_${group.id}">
                                        <strong>${group.groupName}</strong>
                                        <small class="text-muted">(${group.apiCount}个接口)</small>
                                        <br><small class="text-muted">${group.description || '暂无描述'}</small>
                                    </label>
                                </div>
                                <div id="rename_${group.id}" style="display: none;" class="mt-2">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <label class="form-label small">新分组名称</label>
                                            <input type="text" class="form-control form-control-sm" id="newName_${group.id}" value="${group.groupName}" placeholder="请输入新的分组名称">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label small">新描述</label>
                                            <input type="text" class="form-control form-control-sm" id="newDesc_${group.id}" value="${group.description || ''}" placeholder="请输入新的描述">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `).join('');
                    
                    previewDiv.style.display = 'block';
                    document.getElementById('importBtn').disabled = false;
                } else {
                    showAlert('文件预览失败: ' + result.message, 'danger');
                }
            } catch (error) {
                console.error('预览导入失败:', error);
                showAlert('预览导入失败', 'danger');
            }
        }

        // 切换分组重命名区域显示
        function toggleGroupRename(groupId) {
            const checkbox = document.getElementById(`group_${groupId}`);
            const renameDiv = document.getElementById(`rename_${groupId}`);
            
            if (checkbox.checked) {
                renameDiv.style.display = 'block';
            } else {
                renameDiv.style.display = 'none';
            }
        }

        // 切换分组选择显示
        function toggleGroupSelection() {
            const selectedMode = document.querySelector('input[name="importMode"]:checked').value;
            const groupSelection = document.getElementById('groupSelection');
            groupSelection.style.display = selectedMode === 'selected' ? 'block' : 'none';
        }

        // 修改导入数据功能
        async function importData() {
            const form = document.getElementById('importForm');
            const formData = new FormData(form);
            const resultDiv = document.getElementById('importResult');

            // 获取导入模式
            const importMode = document.querySelector('input[name="importMode"]:checked').value;
            formData.append('importMode', importMode);
            
            // 如果是选择性导入，获取选中的分组ID和重命名信息
            if (importMode === 'selected') {
                const selectedCheckboxes = document.querySelectorAll('#groupCheckboxes input:checked');
                    
                if (selectedCheckboxes.length === 0) {
                    showAlert('请至少选择一个分组进行导入', 'warning');
                    return;
                }
                
                const selectedGroups = [];
                const groupRenames = {};
                
                selectedCheckboxes.forEach(checkbox => {
                    const groupId = checkbox.value;
                    selectedGroups.push(groupId);
                    
                    // 获取重命名信息
                    const newName = document.getElementById(`newName_${groupId}`).value.trim();
                    const newDesc = document.getElementById(`newDesc_${groupId}`).value.trim();
                    
                    if (newName) {
                        groupRenames[groupId] = {
                            newName: newName,
                            newDescription: newDesc
                        };
                    }
                });
                
                formData.append('selectedGroupIds', selectedGroups.join(','));
                
                // 如果有重命名信息，添加到请求中
                if (Object.keys(groupRenames).length > 0) {
                    formData.append('groupRenames', JSON.stringify(groupRenames));
                }
            }

            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/mock/data/import`, {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                
                if (result.success) {
                    resultDiv.innerHTML = `
                        <div class="alert alert-success">
                            <i class="bi bi-check-circle"></i>
                            ${result.message}
                        </div>
                    `;
                    // 重新加载数据
                    loadGroups();
                    loadApis();
                } else {
                    resultDiv.innerHTML = `
                        <div class="alert alert-danger">
                            <i class="bi bi-exclamation-circle"></i>
                            ${result.message}
                        </div>
                    `;
                }
                
                resultDiv.style.display = 'block';
            } catch (error) {
                console.error('导入数据失败:', error);
                resultDiv.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="bi bi-exclamation-circle"></i>
                        导入数据失败: ${error.message}
                    </div>
                `;
                resultDiv.style.display = 'block';
            }
        }

        // 修改显示导入模态框函数
        function showImportModal() {
            document.getElementById('importForm').reset();
            document.getElementById('importResult').style.display = 'none';
            document.getElementById('importPreview').style.display = 'none';
            document.getElementById('importBtn').disabled = true;
            new bootstrap.Modal(document.getElementById('importModal')).show();
        }
    </script>

    <!-- 分组批量拉取真实数据模态框 -->
    <div class="modal fade" id="fetchGroupDataModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">批量拉取分组真实数据</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="groupFetchInfo"></div>
                    <div id="groupFetchResult" style="display: none;">
                        <hr>
                        <h6>拉取结果:</h6>
                        <div id="groupFetchDetails"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="confirmFetchGroupData()" id="fetchGroupBtn">
                        <i class="bi bi-cloud-download"></i> 开始拉取
                    </button>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
